<template>
  <div class="myEdit">
    <!-- 顶部栏 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />
    <!-- 头像栏 -->
    <div class="avatar-box">
      <van-image fit="cover" round :src="$store.state.userInfoObj.photo" />
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- cell资料栏 -->
    <van-cell-group>
      <van-cell
        @click="editName"
        title="名称"
        :value="$store.state.userInfoObj.name"
        is-link
      />
      <van-cell
        @click="editGender"
        title="性别"
        :value="$store.state.userInfoObj.gender === 0 ? '男' : '女'"
        is-link
      />
      <van-cell
        @click="editBirth"
        title="生日"
        :value="$store.state.userInfoObj.birthday"
        is-link
      />
    </van-cell-group>

    <!-- 姓名弹出框 -->
    <van-dialog
      @confirm="conEditName"
      @cancel="nameShow = false"
      :beforeClose="beforeClose"
      v-model="nameShow"
      title="编辑姓名"
      show-cancel-button
    >
      <van-field v-model="inputName" placeholder="输入姓名" />
    </van-dialog>

    <!-- 性别弹出框 -->
    <van-popup
      v-model="genderShow"
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-nav-bar
        title="编辑性别"
        left-arrow
        @click-left="genderShow = false"
      />
      <van-cell title="男" is-link @click="conEditGender((gender = 0))" />
      <van-cell title="女" is-link @click="conEditGender((gender = 1))" />
    </van-popup>

    <!-- 生日弹出框 -->
    <van-popup v-model="birthShow" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker
        @cancel="birthShow = false"
        @confirm="conEditBirth"
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>

    <!-- 头像裁剪区 -->
    <div class="avatarCropper" v-if="cropShow">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="200"
        autoCropHeight="200"
      >
      </vueCropper>
      <van-button @click="conCrop" type="primary">裁剪</van-button>
      <van-button @click="cropShow = false" style="right: 0" type="primary"
        >取消</van-button
      >
    </div>
  </div>
</template>

<script>
// 导入裁剪插件
import { VueCropper } from "vue-cropper";
import dayjs from "dayjs";
import { editUserInfoAPI, editAvatarAPI } from "@/api/user";
export default {
  components: {
    VueCropper,
  },
  data() {
    return {
      nameShow: false, // 控制编辑姓名弹出框
      inputName: "", // 输入框内容
      genderShow: false,
      gender: 0, // 控制性别
      birthShow: false,
      cropShow: false,
      // 时间选择器的属性
      minDate: new Date("1949-10-01"),
      maxDate: new Date(),
      currentDate: new Date(),
      cropImg:
        "https://img2.baidu.com/it/u=1319753839,1958584868&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=427",
    };
  },
  async created() {
    // 调用store里获取用户信息的方法
    this.$store.dispatch("getUserInfo");
  },
  methods: {
    // --------------- 编辑姓名 ---------------
    editName() {
      this.nameShow = true;
      this.inputName = this.$store.state.userInfoObj.name;
    },
    // 确认修改姓名
    async conEditName() {
      // 判断内容为空
      if (this.inputName == "") return this.$toast("请输入姓名");
      // 修改服务器数据
      await editUserInfoAPI({
        name: this.inputName,
      });
      // 修改vuex数据，达成页面同步刷新
      this.$store.commit("setUserInfo", {
        // 先展开，单独改一项
        ...this.$store.state.userInfoObj,
        name: this.inputName,
      });
      // 强制关闭弹窗，如果内容为空return了，则不能关闭
      this.nameShow = false;
    },
    // 弹窗关闭前调用的回调函数
    beforeClose(action, done) {
      // 阻止弹窗关闭
      done(false);
    },

    // -------------- 编辑性别 --------------
    editGender() {
      this.genderShow = true;
    },
    async conEditGender(gender) {
      // 修改服务器数据
      await editUserInfoAPI({
        gender,
      });
      // 修改vuex数据，达成页面同步刷新
      this.$store.commit("setUserInfo", {
        // 先展开，单独改一项
        ...this.$store.state.userInfoObj,
        gender,
      });
      // 强制关闭弹窗，如果内容为空return了，则不能关闭
      this.genderShow = false;
    },

    // -------------- 编辑生日 --------------
    editBirth() {
      this.birthShow = true;
      // 字符串转为时间对象
      this.currentDate = new Date(this.$store.state.userInfoObj.birthday);
    },
    async conEditBirth() {
      // 时间对象转化为字符串
      const birthday = dayjs(this.currentDate).format("YYYY-MM-DD");
      await editUserInfoAPI({
        birthday,
      });
      this.$store.commit("setUserInfo", {
        ...this.$store.state.userInfoObj,
        birthday,
      });
      // 强制关闭弹窗，如果内容为空return了，则不能关闭
      this.birthShow = false;
    },

    // -------------- 头像上传 --------------
    // 上传文件后的回调函数
    afterRead(file) {
      this.cropShow = true;
      this.cropImg = file.content;
    },
    conCrop() {
      this.$refs.cropper.getCropBlob(async (data) => {
        // ajax调用接口传文件，依赖FormData
        const img = new FormData();
        img.append("photo", data);
        const res = await editAvatarAPI(img);
        console.log(res);
        this.$store.commit("setUserInfo", {
          ...this.$store.state.userInfoObj,
          photo: res.data.photo,
        });
        this.cropShow = false;
      });
    },
  },
};
</script>

<style scoped lang='less'>
.avatar-box {
  height: 140px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .van-image {
    width: 120px;
    height: 120px;
  }
  .van-uploader {
    position: absolute;
    top: 0;
    left: 0;
    ::v-deep .van-uploader__upload {
      position: absolute;
      top: 0;
      left: 0;
      width: 100vw;
      height: 140px;
      opacity: 0;
    }
  }
}
::v-deep .van-dialog__content {
  border: 1px solid #ddd;
}

.avatarCropper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  .van-button {
    position: absolute;
    bottom: 0;
  }
}
</style>